package zillow;
public class StringToLong {
	
	public StringToLong(){
		
	}
	/**
	 * Given a string, converts the string to a long.
	 * @param s			the input string.
	 * @return			the long number this string represent.
	 * 
	 * Limitations:
	 * 1.Cannot handle the string with space in the middle like "1 23"
	 * 2.Cannot handle the input like "abc" or other non-numeric characters.
	 * 3.Cannot handle the input style like "1,234,333", the commas is used for
	 *	 recognize the number easily.
	 * 4.Once the number is out of the boundary of Long.MAX_VALUE or Long.MIN_VALUE,
	 * 	 this function will throw exception of "Out of boundary".
	 */
	
	public static long stringToLong(String s){
		boolean neg = false;
		
		//ignore the space before number.
		while(s.charAt(0)==' ')
			s = s.substring(1);
		//ignore the space after the number
		while(s.charAt(s.length()-1)==' ')
			s = s.substring(0,s.length()-1);
		
		//if the first digit is "-" or "+", we know the input is 
		//negative number or positive number.
		if (s.charAt(0) == '-' || s.charAt(0)=='+'){
			neg = s.charAt(0)=='-' ? true : false;
			s = s.substring(1);
		}
		long sum = 0;
		for(int i=0;i<s.length();++i){
			int cur = s.charAt(i)-'0';
			//if here is an input character out of the 0~9
			if(cur<0 || cur>9) throw new NumberFormatException("Wrong Input");
			//if the string is out of the boundary of Long 
			//-9223372036854775808-----9223372036854775807
			if(Long.MAX_VALUE/10 <sum || (sum==Long.MAX_VALUE/10 && cur>Long.MAX_VALUE%10 && !neg)
					||(sum==Long.MAX_VALUE/10 && cur>Long.MAX_VALUE%10+1 && neg)){
				throw new NumberFormatException("Out of boundary of Long"); 
			}
			sum = sum*10 + cur;
		}
		return neg ? -1*sum : sum;
	}

	public static void main(String[] args){
		/**
		 * I think the test case should be:
		 * 1.positive number like "123"
		 * 2.negtive number like "-123"
		 * 3."0","000","-0"
		 * 4.""," ","   "
		 * 5."0123","-0123"
		 * 6.max and min:"-9223372036854775808","9223372036854775807"
		 * 7.out of boundary:"9223372036854775808","-9223372036854775809"
		 * 8.space "   123","123   ","   123  "
		 * 9.informal input:"&*&&^*&!!11","1 23 4","1,234","123abc","123.4"
		 */
		String test = "123";
		try {
			long i = stringToLong(test);
			System.out.println(i);
			if(i==123){
				System.out.println("Success.");
			}
			else{
				System.out.println("Failure.");
			}
		} catch (Exception e) {
			System.out.println(e);
		}
			
		
	}

}
